<?php

require_once 'Ethna_Session_Memcache.php';
require_once 'Mobile_Util.php';

class MyApp_Session extends Ethna_Session_Memcache
{
    var $login_method = 'normal';
    
    /**
     *  Smscom_Session
     *
     *  @access public
     *  @param  string  $appid
     *  @param  string  $save_dir
     */
    function MyApp_Session($appid, $save_dir, $logger)
    {
        $ctl = Ethna_Controller::getInstance();
        $config = $ctl->getConfig();
        $session_name = $config->get('session_name');
        $session_expire = (int)$config->get('session_expire');
        
        $this->session_name = empty($session_name) ? "${appid}SESSID" : $session_name;
        $this->session_save_dir = $save_dir;
        $this->logger =& $logger;

        if ($this->session_save_dir != "") {
            session_save_path($this->session_save_dir);
        }

        session_name($this->session_name);
        session_cache_limiter('private, must-revalidate');

        $this->session_start = false;
        if (isset($_SERVER['REQUEST_METHOD']) == false) {
            return;
        }

        if (strcasecmp($_SERVER['REQUEST_METHOD'], 'post') == 0) {
            $http_vars =& $_POST;
        } else {
            $http_vars =& $_GET;
        }
        if (array_key_exists($this->session_name, $http_vars)
            && $http_vars[$this->session_name] != null) {
            $_COOKIE[$this->session_name] = $http_vars[$this->session_name];
        }
        
        $this->expire = $session_expire;
        
        if (Mobile_Util::isMobile()) {
            ini_set('session.use_cookies', 0);
        }
        
        parent::Ethna_Session_Memcache($appid, $save_dir, $logger);
    }
    
    /**
     *
     *  @access public
     *  @param  int     $lifetime
     *  @return bool    true: false:
     */
    function start($lifetime = 0, $anonymous = false)
    {
        $ctl = Ethna_Controller::getInstance();
        $config = $ctl->getConfig();
        $session_cookie_domain = $config->get('session_cookie_domain')? $config->get('session_cookie_domain') : $_SERVER['SERVER_NAME'];
        if ($this->session_start) {
            $_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
            $_SESSION['__anonymous__'] = $anonymous;
            $_SESSION['__nonce__'] = md5($session_cookie_domain . $_SERVER['HTTP_USER_AGENT']);
            $_SESSION['__login_method__'] = $this->login_method;
            return true;
        }

        if (is_null($lifetime)) {
            ini_set('session.use_cookies', 0);
        } else {
            ini_set('session.use_cookies', 1);
        }

        session_set_cookie_params($lifetime);
        session_id(Ethna_Util::getRandom());
        session_start();
        $_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
        $_SESSION['__anonymous__'] = $anonymous;
        $_SESSION['__nonce__'] = md5($session_cookie_domain . $_SERVER['HTTP_USER_AGENT']);
        $_SESSION['__login_method__'] = $this->login_method;
        $this->session_start = true;

        return true;
    }
    
    /**
     *
     *  @access public
     *  @return bool    true: false:
     */
    function isValid()
    {
        if (!$this->session_start) {
            if (!empty($_COOKIE[$this->session_name]) || session_id() != null) {
                setcookie($this->session_name, "", 0, "/");
            }
            return false;
        }
        
        if (isset($_SESSION['__login_method__']) && $_SESSION['__login_method__'] == "normal") {
            $ctl = Ethna_Controller::getInstance();
            $config = $ctl->getConfig();
            $session_cookie_domain = $config->get('session_cookie_domain')? $config->get('session_cookie_domain') : $_SERVER['SERVER_NAME'];
            if (isset($_SESSION['__nonce__']) && $_SESSION['__nonce__'] != md5($session_cookie_domain . $_SERVER['HTTP_USER_AGENT'])) {
                $this->logger->log(LOG_ALERT, "session nonce validation failed [%s] - [%s]", $_SESSION['__nonce__'], md5($_SERVER['SERVER_NAME'] . $_SERVER['HTTP_USER_AGENT']));
                
                $this->destroy();
                
                return false;
            }
            
            if (!Mobile_Util::isMobile()) {
                if (!isset($_SESSION['REMOTE_ADDR'])
                    || $this->_validateRemoteAddr($_SESSION['REMOTE_ADDR'],
                                                  $_SERVER['REMOTE_ADDR']) == false) {
                    if (isset($_SESSION['REMOTE_ADDR'])) {
                        $this->logger->log(LOG_ALERT, "session IP validation failed [%s] - [%s]", $_SESSION['REMOTE_ADDR'], $_SERVER['REMOTE_ADDR']);
                    }
                    
                    $this->destroy();
                    
                    return false;
                }
            }
        }

        return true;
    }
    
    function attach($session_id)
    {
        session_id($session_id);
        $this->session_start = session_start();
        return $this->session_start;
    }
    
    function setLoginMethod($type)
    {
        $this->login_method = $type;
    }
}
?>